package com.zkzx.operation.api.service.authorization;

import com.zkzx.common.global.Global;
import com.zkzx.operation.api.mapper.RoleMapper;
import com.zkzx.operation.api.mapper.entity.Role;
import com.zkzx.operation.api.mapper.entity.User;
import com.zkzx.operation.api.mapper.entity.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/**
 * 登录验证帐号密码用
 * Created by young on 2021/4/26.
 */
@Component
public class MyUserDetailsService implements UserDetailsService {

    @Resource
    RoleMapper roleMapper;

    @Autowired
    UserMapperService userMapperService;

    @Autowired
    UserRoleService userRoleService;


    @Override
    public UserDetails loadUserByUsername(String username){
        //查询用户
        User userInfo = userMapperService.getByCode(username);
        if (userInfo == null) {
            throw new BadCredentialsException("用户不存在");
        }

        // 查询角色
        UserRole userRole = userRoleService.getByUserId(userInfo.getId());
        if (userRole == null) {
            throw new BadCredentialsException("用户角色不存在");
        }

        // 查询角色详情
        Role role = roleMapper.selectByPrimaryKey(userRole.getRoleid());

        // 构造用户角色权限列表
        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(role.getId().toString()));

        // 返回带有用户权限信息的User（从左到右参数，用户名，密码，账户未禁用，账户未过期，密码未过期，账号未锁定，权限列表）
        org.springframework.security.core.userdetails.User user =
                new org.springframework.security.core.userdetails.User(userInfo.getId().toString(),
                        userInfo.getPwd(), getBoolean(userInfo.getIsenabled()), getBoolean(userInfo.getIsaccountnotexpired()),
                        getBoolean(userInfo.getIscredentialsnonexpired()), getBoolean(userInfo.getIsaccountnotlocked()), authorities);
        return new MyUserDetails(user);
    }

    private Boolean getBoolean(byte value){
       return  value == Global.ONE;
    }
}
